package utils

import (
	"fmt"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/ipipdotnet/ipdb-go"
)

// GetClientIP 获取用户请求ip
func GetClientIP(c *gin.Context) string {
	//获取用户ip
	reqIp := c.ClientIP()
	if reqIp == "::1" {
		reqIp = "127.0.0.1"
	}

	//todo 临时解决（后续看看如何处理下），原因：uniapp 通过ajax发送post请求时候，如果没有下面代码，ip一直都返回的是127.0.0.1，没有获取到真正用户ip
	if reqIp == "127.0.0.1" {
		reqIp = c.Request.Header.Get("X-Forwarded-For")
		if reqIp == "" {
			reqIp = "127.0.0.1"
		}
	}
	return reqIp
}

func GetClientIPNew(c *gin.Context) string {
	ClientIP := c.ClientIP()
	//fmt.Println("ClientIP:", ClientIP)
	RemoteIP := c.RemoteIP()
	//fmt.Println("RemoteIP:", RemoteIP)
	ip := c.Request.Header.Get("X-Forwarded-For")
	if strings.Contains(ip, "127.0.0.1") || ip == "" {
		ip = c.Request.Header.Get("X-real-ip")
	}
	if ip == "" {
		ip = "127.0.0.1"
	}
	if RemoteIP != "127.0.0.1" {
		ip = RemoteIP
	}
	if ClientIP != "127.0.0.1" {
		ip = ClientIP
	}
	return ip
}

// ParseIp 使用IP识别库将IP转换为城市
func ParseIp(ip string) *ipdb.CityInfo {
	db, err := ipdb.NewCity("./config/city.free.ipdb")
	if err != nil {
		fmt.Println(1, err.Error())
		return nil
	}

	err = db.Reload("./config/city.free.ipdb")
	if err != nil {
		fmt.Println(2, err.Error())

		return nil
	}

	c, err := db.FindInfo(ip, "CN")
	if err != nil {
		return nil
	}
	return c
}
